﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLayer.ExtensionMethod
{
	public static class DataBase
	{
		public static string toInsertQueryString(this object obj, string _nomeTabela)
		{
			Type type = obj.GetType();
			PropertyInfo[] properties = type.GetProperties();

			string separador = ", ";
			StringBuilder strB = new StringBuilder();
			strB.Append("insert into " + _nomeTabela + " (");

			List<string> nome_Campos = new List<string>();
			List<string> valores_Campos = new List<string>();

			for (int iProperty = 0; iProperty < properties.Count(); iProperty++)
			{
				PropertyInfo property = properties[iProperty];

				if (iProperty > 0)
				{
					if (property.GetValue(obj, null) != null)
					{
						nome_Campos.Add(((DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true)[0]).Name);

						var field_type = property.GetValue(obj, null);

						if ((field_type.GetType().Equals(typeof(string))) || (field_type.GetType().Equals(typeof(DateTime))))
						{
							string campo = "\"" + property.GetValue(obj, null).ToString() + "\"";
							valores_Campos.Add(campo);
						}
						else
							valores_Campos.Add(property.GetValue(obj, null).ToString());
					}
				}
			}

			for (int iCampos = 0; iCampos < nome_Campos.Count; iCampos++)
				if (iCampos < nome_Campos.Count - 1)
					strB.Append(nome_Campos[iCampos] + separador);
				else
					strB.Append(nome_Campos[iCampos]);

			strB.Append(") values (");

			for (int iValores = 0; iValores < valores_Campos.Count; iValores++)
				if (iValores < valores_Campos.Count - 1)
					strB.Append(valores_Campos[iValores] + separador);
				else
					strB.Append(valores_Campos[iValores] + ")");

			return strB.ToString();
		}

	}
}
